package messages

import (
	"bytes"
	"crypto/tls"
	"encoding/json"
	"gitee.com/captials-team/ubdframe/src/domain/configstc"
	"io"
	"net/http"
	"time"
)

// DingTalkRobotSender 钉钉机器人
// 详见官方文档：https://open.dingtalk.com/document/isvapp/message-type
type DingTalkRobotSender struct {
	cnf configstc.WebHookConfig

	client *http.Client
}

func NewDingTalkRobotSender(cnf configstc.WebHookConfig) *DingTalkRobotSender {
	client := &http.Client{
		Timeout: 3 * time.Second,
		Transport: &http.Transport{
			TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
		},
	}

	return &DingTalkRobotSender{
		cnf:    cnf,
		client: client,
	}
}

func (s *DingTalkRobotSender) OriginSend(params map[string]interface{}) ([]byte, error) {
	reqBody, err := json.Marshal(params)
	if err != nil {
		return nil, err
	}
	req, err := http.NewRequest(http.MethodPost, s.cnf.Url, bytes.NewReader(reqBody))
	if err != nil {
		return nil, err
	}
	req.Header.Add("Content-Type", "application/json")
	resp, err := s.client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	body, _ := io.ReadAll(resp.Body)
	return body, nil
}
